package me.pplay.playtalk.activity.friends;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import me.pplay.playtalk.ApplicationTrans;
import me.pplay.playtalk.R;
import me.pplay.playtalk.activity.BaseActivity;
import me.pplay.playtalk.activity.ChatConversationActivity;
import me.pplay.playtalk.adapter.CommonAdapter;
import me.pplay.playtalk.bean.CommonControlID;
import me.pplay.playtalk.callback.CommonAdapterOnClickCallBack;
import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.protocol.DataCallBack;
import me.pplay.playtalk.protocol.TpChat;
import me.pplay.playtalk.protocol.bean.RspData;
import me.pplay.playtalk.protocol.bean.TPBuddyinfo;
import me.pplay.playtalk.util.BuddyInfoUtil;
import me.pplay.playtalk.util.LogManager;
import me.pplay.playtalk.view.DialogMenu;
import me.pplay.playtalk.util.SkyUtil;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;

public class FriendsActivity extends BaseActivity {
	private RelativeLayout layout_bar;
	private ImageButton backBtn,searchBtn;
	private EditText search_et;
	private DialogMenu menuDialog;
	private int clickPosition = 0;
	
	private final int SETADAPTER = 1;
	private List<Map<String, Object>> mData;
	private List<Map<String, Object>> searchData;
	private ListView list;
	private TpChat tpChat;
//	private FriendsBroadcaseReceiver receiver;
	private CommonAdapter adapter;
	
	private boolean isSearch = false;
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case TpChat.CHAT_GETGROUP_OK:
			case TpChat.CHAT_GETBUDDIES_OK:
				getData();
			case SETADAPTER:
				adapter.notifyDataSetChanged();
				break;
			case Globals.SETADAPTER:
				getData();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_friends);
		super.SetOnBackClickListener((ImageButton)findViewById(R.id.btn_back));
		findViews();
		initDatas();
		ApplicationTrans appState = (ApplicationTrans) getApplicationContext();
		tpChat = appState.getTpChat();
		getData();
		CommonControlID holderId = new CommonControlID();
		holderId.itemLayout = R.layout.layout_friendslist;
		holderId.leftImgId = R.id.friends_img;
		holderId.rightImgId = R.id.friends_add;
		holderId.leftStrId = R.id.friends_title;
		holderId.leftStr1Id = R.id.friends_topic;
		adapter = new CommonAdapter(FriendsActivity.this, searchData, holderId, new CommonAdapterOnClickCallBack() {

			@Override
			public void OnClickCallback(int pos, int ViewId, View v) {
				// TODO Auto-generated method stub
				LogManager.LogShow("FriendsActivity", "OnClickCallback position " + pos);

			}
		});
		list = (ListView) this.findViewById(R.id.friends_list); // 联系人ListView
		list.setAdapter(adapter);// 将数据适配器与Activity进行绑定
		clickEvents();
	}

	private void findViews(){
		layout_bar	= (RelativeLayout)findViewById(R.id.layout_bar);
		backBtn		= (ImageButton)findViewById(R.id.backBtn);
		searchBtn		= (ImageButton)findViewById(R.id.searchBtn);
		search_et	= (EditText)findViewById(R.id.search_et);
	}
	
	private void initDatas(){
		isSearch  = getIntent().getBooleanExtra("isSearch", false);
		layout_bar.setVisibility(View.VISIBLE);
		if(!isSearch){//
			search_et.setVisibility(View.INVISIBLE);
			return;
		}
		searchBtn.setVisibility(View.INVISIBLE);
		search_et.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if(mData == null)
					return;
				searchData.clear();
				int size = mData.size();
				for (int i = 0; i < size; i++) {
					Map<String, Object> map = mData.get(i);
					String alias = (String)map.get("leftStr");
					if(alias.contains(s.toString().trim()))
						searchData.add(map);
				}
				adapter.notifyDataSetChanged();
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
			
			@Override
			public void afterTextChanged(Editable s) { }
		});
		
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
//		unregisterReceiver(receiver);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
//		receiver = new FriendsBroadcaseReceiver();
//		String actionStr = "";
//		actionStr = PlayTalkService.MESSAGE_CHATLIST_BRODCASE;
//		IntentFilter filter = new IntentFilter(actionStr);
//		registerReceiver(receiver, filter);
	}

	private void getData() {
		mData 		= new ArrayList<Map<String,Object>>();
		searchData	= new ArrayList<Map<String,Object>>();
		mData.clear();
		searchData.clear();
		LinkedList<TPBuddyinfo> flist = tpChat.tp_chat_getfriendslist();
		
		if (flist != null) {
			for (TPBuddyinfo g : flist) {
				LogManager.LogShow("FriendsActivity", "g.getName() " + g.getName());
				Map<String, Object> map = new HashMap<String, Object>();
				int id = g.getAvatarid();
				if(id<0||id>19)
					id = 0;
//				if (g.getServer_alias().length() > 0)
//					map.put("leftStr", g.getServer_alias());
//				else if (g.getAlias().length() > 0)
//					map.put("leftStr", g.getAlias());
//				else if (g.getName().length() > 0)
//					map.put("leftStr", g.getName());
//				else
//					map.put("leftStr", "" + g.getSkyid());
				map.put("leftStr", BuddyInfoUtil.getAlias(g));
				if (g.getSignature().length() > 0)
					map.put("leftStr1", g.getSignature());

				try {
					int drwableid = R.drawable.avatarf;

					if (g.getSex() != 1)
						drwableid = R.drawable.class.getDeclaredField("avatarf").getInt(this);
					else
						drwableid = R.drawable.class.getDeclaredField("avatar" + id).getInt(this);
					Drawable mDrawable = getResources().getDrawable(drwableid);
					if (g.getStatus() == TpChat.TP_STATUS_AVAILABLE) {
						map.put("leftImgDrwable", mDrawable);
					} else {
						map.put("leftImgDrwable", SkyUtil.setGrayDrawble(mDrawable));
					}
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					map.put("leftImg",R.drawable.friends_default);
					e.printStackTrace();
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					map.put("leftImg",R.drawable.friends_default);
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					map.put("leftImg",R.drawable.friends_default);
					e.printStackTrace();
				} catch (NoSuchFieldException e) {
					// TODO Auto-generated catch block
					map.put("leftImg",R.drawable.friends_default);
					e.printStackTrace();
				}
				map.put("rightImg", R.drawable.commnutiy_chat);
				map.put("obj", g);
				mData.add(map);
				searchData.add(map);
			}
		}

		// Map<String, Object> map = new HashMap<String, Object>();
		// map.put("leftStr", "G1");
		// map.put("leftStr1", "google 1");
		// map.put("leftImg", R.drawable.friends_default);
		// map.put("rightImg", R.drawable.addfriends);
		// listData.add(map);
		// map = new HashMap<String, Object>();
		// map.put("leftStr", "G2");
		// map.put("leftStr1", "google 2");
		// map.put("leftImg", R.drawable.friends_default);
		// map.put("rightImg", R.drawable.addfriends);
		// listData.add(map);
		// map = new HashMap<String, Object>();
		// map.put("leftStr", "G3");
		// map.put("leftStr1", "google 3");
		// map.put("leftImg", R.drawable.friends_default);
		// map.put("rightImg", R.drawable.addfriends);
		// listData.add(map); 
	}

	private void clickEvents() {
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Map<String, Object> map = mData.get(arg2);
				TPBuddyinfo g = (TPBuddyinfo) map.get("obj");
//				String alias;
				if (g != null) {
//					if (g.getServer_alias().length() > 0)
//						alias = g.getServer_alias();
//					else if (g.getAlias().length() > 0)
//						alias = g.getAlias();
//					else if (g.getName().length() > 0)
//						alias = g.getName();
//					else
//						alias = "" + g.getSkyid();

					Intent intent = new Intent();
					Bundle bundle = new Bundle();
					bundle.putString("from", "tpbuddyinfo");
					bundle.putInt("skyid", g.getSkyid());
					bundle.putString("icon", g.getAvatar_fpath());
					bundle.putSerializable("skyname", BuddyInfoUtil.getAlias(g)); 
					intent.putExtras(bundle);
					intent.setClass(FriendsActivity.this, ChatConversationActivity.class);
					startActivity(intent);
				}
			}
		});
		if(!isSearch){
			list.setOnItemLongClickListener(new OnItemLongClickListener() {
	
				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					clickPosition	= arg2;
					if(menuDialog == null){
						menuDialog = new DialogMenu(FriendsActivity.this, FriendsActivity.this.findViewById(R.id.rootView), 
								R.drawable.dialog_icon, getString(R.string.attach), new int[]{R.drawable.dialog_delete, R.drawable.dialog_view_details_icon}, getResources().getStringArray(R.array.array_friends_menu), new DataCallBack(){

							@Override
							public void Callback(int result, RspData resultdata, Object obj) {
								menuOption(result);
							}
						}); 
					}
					menuDialog.show(true);
					return false;
				}
			});
			searchBtn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent  = new Intent(FriendsActivity.this, FriendsActivity.class);
					intent.putExtra("isSearch", true);
					startActivity(intent);
				}
			});
		}
		
		backBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				FriendsActivity.this.finish();
			}
		});
		
	}

//	class FriendsBroadcaseReceiver extends BroadcastReceiver {
//
//		@Override
//		public void onReceive(Context context, Intent intent) {
//			// TODO Auto-generated method stub
//			Bundle bundle = intent.getExtras();
//			int typeFrom = bundle.getInt("result");
//			int type = ((RspData)bundle.getSerializable("resultdata")).getSubid();
//			// TpNotiNode noti_node = (TpNotiNode)
//			// bundle.getSerializable("object");
//			Log.v("FriendsActivity", "FriendsBroadcaseReceiver = " + typeFrom);
//			if(TpChat.CHAT_NOTIFICATION_OK == typeFrom&&type == ProtocolType.NotiType.TP_NOTIFICATION_CHAT_BSTATUS)
//				typeFrom = TpChat.CHAT_GETBUDDIES_OK;
//			switch (typeFrom) {
//			case TpChat.CHAT_GETGROUP_OK:
//			case TpChat.CHAT_GETBUDDIES_OK:
//				// 通知界面刷新
//				getData();
//				handler.sendEmptyMessage(typeFrom);
//				break;
//			}
//		}
//	}
	
	private void menuOption(int index){
		Map<String, Object> map = searchData.get(clickPosition);
		TPBuddyinfo buinfo = (TPBuddyinfo) map.get("obj");
		switch (index) {
		case 0:		//Delete
			tpChat.tp_chat_remove_buddy(buinfo.getSkyid(), tpChat.tp_chat_getfriendsgid());
			mData.remove(map);
			searchData.remove(map);
			handler.sendEmptyMessage(SETADAPTER);
			break;
		case 1:		//Ignore
			tpChat.tp_chat_move_buddy(buinfo.getSkyid(), tpChat.tp_chat_getfriendsBackListGid());
			mData.remove(map);
			searchData.remove(map);
			handler.sendEmptyMessage(SETADAPTER);
			break;
		}
		menuDialog.show(false);
	}
	
	
	
	
	
	
}









